package com.trytech.mongoocrawler.server.pipeline;

import com.trytech.mongoocrawler.server.CrawlerContext;
import com.trytech.mongoocrawler.server.common.db.CrawlerDataSource;
import com.trytech.mongoocrawler.server.common.db.MySqlDruidDataSource;
import com.trytech.mongoocrawler.server.entity.LianjiaItem;
import org.elasticsearch.client.Client;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by coliza on 2017/6/15.
 */
public class LianjiaPipline extends AbstractPipeline<List<LianjiaItem>>{
    private Client client;
    @Override
    public void store(List<LianjiaItem> lianjiaItemList) throws SQLException, ClassNotFoundException {
        for(LianjiaItem lianjiaItem:lianjiaItemList) {
            String sql = "insert into lj_house(`C_TITLE`,`C_LOCATION`,`C_TYPE`,`C_FLOORSPACE`,`C_PRICE`,`C_UNIT_PRICE`) values('" + lianjiaItem.getTitle() + "','" + lianjiaItem.getLocation() + "','" + lianjiaItem.getType() +
                    "','" + lianjiaItem.getFloorSpace() + "'," + lianjiaItem.getPrice().toString() + "," + lianjiaItem.getUnitPrice().toString() + ")";
            System.out.println(sql);
            MySqlDruidDataSource dataSource = (MySqlDruidDataSource)getDataSource();
            dataSource.insert(sql);
        }
//        try {
//            Settings settings = Settings.builder().put("cluster.name", "trytech-es").put("client.transport.sniff", false).build();
//            if (client == null) {
//                client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("123.57.219.78"), 9200));
//            }
//            BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
//            IndexRequestBuilder indexRequestBuilder = null;
//            //根据请求对象bodyList, 组织bulkRequestBuilder对象
//            String indexId = "";
//            Map<String, Object> bodyMap = null;
//            for (int index = 0; index < lianjiaItemList.size(); index++) {
//                LianjiaItem lianjiaItem = lianjiaItemList.get(index);
//                if (lianjiaItem == null) {
//                    break;
//                }
//                bodyMap = lianjiaItem.toMap();
//                //组织索引对象id
//                indexRequestBuilder = client.prepareIndex("house/lianjia", String.valueOf(index)).setSource(bodyMap);
//                bulkRequestBuilder.add(indexRequestBuilder);
//            }
//            //批量更新执行
//            BulkResponse bulkResponse = bulkRequestBuilder.execute().actionGet();
//            if (bulkResponse.hasFailures()) {
//                System.out.println("新建索引成功！");
//            } else {
//                System.out.println("新建索引失败！");
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }
    }

    @Override
    public CrawlerDataSource getDataSource() {
        return CrawlerContext.getConfig().getConfigBean().getDataSource(DATASOURCE_NAME);
    }
}
